package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

public class WxTest {
	public static String WX_APPID = "wx32ecb71139189171";
	public static String WX_SECRET = "94eb0f21f1bb2947fded40d09c4169b9";
	
	public static String getToken(String code) throws IOException {
		URL tokenUrl = new URL("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WX_APPID+"&secret="+WX_SECRET+"&code="+code+"&grant_type=authorization_code");
		HttpURLConnection tokenCon = (HttpURLConnection) tokenUrl.openConnection();
		tokenCon.setRequestMethod("GET");
		tokenCon.setDoOutput(true);
		tokenCon.setDoInput(true);
		tokenCon.setConnectTimeout(5000);
		tokenCon.setReadTimeout(5000);
		tokenCon.setUseCaches(false);
		tokenCon.connect();
		
		int return_code = tokenCon.getResponseCode();
		
		String msg = "";
		if (return_code == 200) { // 正常响应
			// 从流中读取响应信息
			BufferedReader reader = new BufferedReader(new InputStreamReader(tokenCon.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) { // 循环从流中读取
				msg += line + "\n";
			}
			reader.close(); // 关闭流
		}
		System.out.println(msg);
		
		return msg;
	}
	
	public static void main(String[] args) throws IOException {
		String code = "061NHV4d0kCl5u1SdM7d0B3a5d0NHV42";
		System.out.println(JSONObject.class);
//		String tokenMsg = getToken(code);
//		JSONObject json = JSONObject.fromObject("{\"errcode\":40163,\"errmsg\":\"code been used, hints: [ req_id: sPV4fA0242th19 ]\"}");
//		System.out.println(json);
	}
}
